package cn.backflow.admin.service;

import cn.backflow.admin.common.pagination.Page;
import cn.backflow.admin.common.pagination.PageRequest;
import cn.backflow.admin.entity.FileMapping;
import com.qiniu.common.QiniuException;
import com.qiniu.storage.model.FileInfo;
import cn.backflow.admin.dao.FileMappingDao;
import cn.backflow.admin.service.base.BaseService;
import cn.backflow.lib.thirdpart.QiniuUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class FileMappingService extends BaseService<FileMapping, java.lang.Integer> {

    private QiniuUtil qiniuUtil = QiniuUtil.getInstance(QiniuUtil.Namespace.ADMIN);

    @Autowired
    private FileMappingDao fileMappingDao;

    public int save(List<FileMapping> mappings) {
        if (mappings == null || mappings.isEmpty())
            return 0;
        return fileMappingDao.save(mappings);
    }

    public List<FileMapping> findByKeys(List<String> keys) {
        if (keys == null || keys.isEmpty()) return Collections.emptyList();
        return fileMappingDao.findByKeys(keys);
    }

    public Collection<FileMapping> findByFileInfos(FileInfo[] infos) {
        List<String> keys = new ArrayList<>(infos.length);
        for (FileInfo info : infos) {
            keys.add(info.key);
        }
        Map<String, FileMapping> map = findMapByKeys(keys);

        List<FileMapping> list = new ArrayList<>();
        for (FileInfo info : infos) {
            if (map.containsKey(info.key)) {
                list.add(map.get(info.key));
            } else {
                list.add(FileMapping.fromFileInfo(info));
            }
        }
        return list;
    }

    public Map<String, FileMapping> findMapByKeys(List<String> keys) {
        return fileMappingDao.findMapByKeys(keys, "key");
    }

    public Page<FileMapping> findByFolder(String folder, int pageNumber, int pageSize) {
        PageRequest pr = new PageRequest();
        pr.addFilter("folder", folder);
        pr.setSortColumns("id desc");
        pr.setPageNumber(pageNumber);
        pr.setPageSize(pageSize);
        return fileMappingDao.findByPageRequest(pr);
    }

    public int deleteByKeys(String[] keys) throws QiniuException {
        return fileMappingDao.deleteByKeys(keys);
    }

    @Override
    public int deleteBatch(Collection<Integer> integers) throws DataAccessException {
        return super.deleteBatch(integers);
    }
}